define(["jquery", "tagsinput"], function ($, tagsinput) {
    const layer = layui.layer;
    const tree = layui.tree;
    let index;
    let selectedItem = [];
    let inputTags;
    let group=[];
    let memberList=[];
    let init;
    let _callback;
    let currentSelect = {
        group_id: 0,
        tree_id: 0,
        group: {},
        tree:{},
        inputs:{},
        selectItems: []
    };
    let selectbox = {
        init(){
            let that = $('[data-role="select-box"]');
            if(that.length > 0){
                init = JSON.parse(that.attr('data-select-box-initUrl')) || {};
                inputTags = that.tagsinput()[0];
                currentSelect.inputs = inputTags;
                currentSelect.selectItems = [];
            }
        },
        renderNav() {
            let html = '';
            $.get(init.navUrl).then(({ data })=>{
                group = data;
                data.map((item, index) => {
                    if(index === 0){
                        html += `<li class="active" data-key='${JSON.stringify(item)}'>${item.title}</li>`;
                        currentSelect.group_id = item.id;
                        currentSelect.group = item;
                    }else{
                        html += `<li data-key='${JSON.stringify(item)}'>${item.title}</li>`;
                    }
                });
                $('.breadcrumb-list').html(html);
                this.renderLeft(currentSelect.group_id);
            });
        },
        renderLeft(id = 0){
            let that = this;
                layer.load();
            $.get(init.leftUrl,{data_id: id}).then(({data: dataList }) => {
                layer.closeAll('loading');
                let first = dataList[0]['children'][0];
                currentSelect.tree_id = first.id;
                currentSelect.tree = first;
                tree.render({
                    elem: '#test1',
                    showCheckbox: true,
                    showLine: false,
                    data: dataList,
                    onlyIconControl: false,
                    async oncheck({ data, checked}) {
                        if (checked) {
                            currentSelect.tree_id = data.id;
                            currentSelect.tree = data;
                            await that.renderMember(data.id, data.title)
                        }else{
                            if(currentSelect.selectItems[data.id]){
                                currentSelect.selectItems[data.id].map(item =>{
                                    that.remove(item.title)
                                });
                                that.del(currentSelect.selectItems, currentSelect.tree.id, true);
                            }
                            await that.renderMember(data.id, data.title, false)
                        }
                    }
                });
            });
        },
        async renderMember(id=0, txt ='', r = true){
            $('#current').text(txt);
            layer.load();
            if(r){
                let {data: dataList } = await $.get(init.memberUrl,{data_id: id});
                memberList = dataList;
            }else{
                memberList = [];
            }
            layer.closeAll('loading');
            let html = '';
            memberList.map(item => {
                let init = selectedItem.find(item1 => item1 === item.title);
                if(init){
                    html += `<li class="active"><span class="ok">✔</span><a href="javascript:;" data-key='${JSON.stringify(item)}'>${item.title}</a></li>`;
                }else{
                    html += `<li><a href="javascript:;" data-key='${JSON.stringify(item)}'>${item.title}</a></li>`;
                }
            });
            $('.user-list').html(html);
            $('ul.toolbar>li:eq(1)').trigger('click');
        },
        search(q){
            let results = q ? memberList.filter(item => item.title.toLowerCase().indexOf(q.toLowerCase()) === 0) : memberList;
            let html = '';
            results.map(item => {
                let init = selectedItem.find(item1 => item1 === item.title);
                if(init){
                    html += `<li class="active"><span class="ok">✔</span><a href="javascript:;" data-key='${JSON.stringify(item)}'>${item.title}</a></li>`;
                }else{
                    html += `<li><a href="javascript:;" data-key='${JSON.stringify(item)}'>${item.title}</a></li>`;
                }
            });
            $('.user-list').html(html);
            $('ul.toolbar>li:eq(1)').trigger('click');
        },
        del(list = [], name, key = false) {
            if(key){
                list.map((item, index) => {
                    if(index === name){
                        list.splice(index, 1);
                    }
                });
            }else{
                list.map((item, index) => {
                    if(item === name){
                        list.splice(index, 1);
                    }
                });
            }
            return this;
        },
        delArr(list = [], name) {
            list.map((item, index) => {
                if(item.title === name){
                    list.splice(index, 1);
                }
            });
            return this;
        },
        addArr(list = [], name) {
            list.push(name);
            return this;
        },
        arrIds(list = []) {
            let _ids = [];
            list.map(item => {
                item.map(item =>{
                    if(!_ids.includes(item.id)){
                        _ids.push(item.id);
                    }
                });
            });
            return _ids;
        },
        add(text, ele = '', data = null) {
            if(text){
                let it = selectedItem.find(item => item === text);
                if(!it){
                    selectedItem.push(text);
                    inputTags.add(text);
                    ele?ele.addClass('active').html(`<span class="ok">✔</span><a href="javascript:;" data-key='${data?JSON.stringify(data):''}'>${text}</a>`):'';
                }
            }
            return this;
        },
        remove(text, ele = '', data = null) {
            if(text){
                this.del(selectedItem, text);
                inputTags.remove(text);
                ele?ele.removeClass('active').html(`<a href="javascript:;" data-key='${data?JSON.stringify(data):''}'>${text}</a>`):'';
            }
            return this;
        },
        removeAll(){
            inputTags.removeAll();
            currentSelect.selectItems = [];
            layer.close(index);
            return this;
        },
        reduce(text, ele = '', data = null){
            if(text){
                let it = selectedItem.find(item => item === text);
                if(!it){
                    this.addArr(currentSelect.selectItems[currentSelect.tree_id], data);
                    selectedItem.push(text);
                    inputTags.add(text);
                    ele?ele.addClass('active').html(`<span class="ok">✔</span><a href="javascript:;" data-key='${data?JSON.stringify(data):''}'>${text}</a>`):'';
                } else {
                    this.delArr(currentSelect.selectItems[currentSelect.tree_id], text);
                    this.del(selectedItem, text);
                    inputTags.remove(text);
                    ele?ele.removeClass('active').html(`<a href="javascript:;" data-key='${data?JSON.stringify(data):''}'>${text}</a>`):'';
                }
            }
            return this;
        },
        console() {
            console.log('selectInput', this.getTagsInput());
            console.log('selectItems', this.getSelectItems());
            console.log('currentTree', this.getCurrentTree());
        },
        getSelectItems(){
            return currentSelect.selectItems;
        },
        getTagsInput(){
            return currentSelect.inputs;
        },
        getCurrentTree(){
            return currentSelect.tree;
        },
        watch(obj, cb) {
            let that = this;
            if (typeof obj === "object") {
                for (let key in obj) {
                    if (typeof obj[key] === "object") {
                        obj[key] = that.watch(obj[key], cb);
                    }
                }
            }
            return new Proxy(obj, {
                /**
                 * @param {Object, Array} target 设置值的对象
                 * @param {String} key 属性
                 * @param {any} value 值
                 * @param {Object} receiver this
                 */
                set: function (target, key, value, receiver) {
                    if (typeof value === "object") {
                        value = that.watch(value, cb);
                    }
                    let cbType = target[key] == undefined ? "create" : "modify";
                    //排除数组修改length回调
                    if (!(Array.isArray(target) && key === "length")) {
                        cb(cbType, { target, key, value });
                    }
                    return Reflect.set(target, key, value, receiver);
                },
                deleteProperty(target, key) {
                    cb("delete", { target, key });
                    return Reflect.deleteProperty(target, key);
                }
            });
        }
    };

    $('body').on('click', '.bootstrap-tagsinput>input', function (e) {
        e.preventDefault();
        let that = $('input[data-role="select-box"]');
        let width = that.attr('data-select-box-width') || '650px';
        let height = that.attr('data-select-box-height') || '500px';
        let cb = that.attr('data-select-cb');
        selectedItem = [];
        currentSelect.selectItems = currentSelect._selectItems = [];
        selectbox.removeAll();
        index = layer.open({
            type: 1,
            content: `<div class="selected1" style=" height: ${height}">
        <div class="breadcrumb">
            <ul class="breadcrumb-list"></ul>
            <input type="text" name="keywords" autocomplete="off">
        </div>
        <div class="content">
            <div class="content-left" id="test1"></div>
            <div class="content-right">
                <ul class="toolbar">
                    <li><b><a href="javascript:;" id="current"></a></b></li>
                    <li><b><a href="javascript:;">全部添加</a></b></li>
                    <li><b><a href="javascript:;">全部删除</a></b></li>
                </ul>
                <ul class="user-list"></ul>
            </div>
        </div>
    </div>`,
            area: [width, height],
            success(){
                selectbox.renderNav();
                $('input[name="keywords"]').bind('input propertychange',function (e) {
                    selectbox.search(this.value)
                });
                _callback = eval("("+ cb +")");
            }
        });
    });

    $(document).on('click', 'ul.user-list>li', function (e) {
        e.preventDefault();
        let that = $(this).find('a');
        let text = that.text();
        let data = JSON.parse(that.attr('data-key'));
        selectbox.reduce(text, $(this), data);
        _callback(selectbox.arrIds(currentSelect.selectItems));
    });

    $(document).on('click', 'ul.breadcrumb-list>li', function (e) {
        e.preventDefault();
        let obj = $(this).attr('data-key');
        let data = JSON.parse(obj);
        $(this).addClass('active').siblings().removeClass('active');
        selectbox.renderLeft(data.id);
        _callback(selectbox.arrIds(currentSelect.selectItems));
    });

    $(document).on('click', 'ul.toolbar>li:eq(1)', function (e) {
        e.preventDefault();
        let _items = [];
        $('ul.user-list>li').each((index, item) =>{
            let that = $(item).find('a');
            let text = that.text();
            let data = JSON.parse(that.attr('data-key'));
            _items.push(data);
            selectbox.add(text, $(item), data);
        });
        if(_items.length > 0 ){
            currentSelect.selectItems[currentSelect.tree_id] = _items;
        }
        _callback(selectbox.arrIds(currentSelect.selectItems));
    });

    $(document).on('click', 'ul.toolbar>li:eq(2)', function (e) {
        e.preventDefault();
        if(selectedItem.length > 0){
            $('ul.user-list>li').each((index, item) =>{
                let that = $(item).find('a');
                let text = that.text();
                let data = JSON.parse(that.attr('data-key'));
                selectbox.remove(text, $(item), data);
            });
            selectbox.del(currentSelect.selectItems, currentSelect.tree.id, true);
            _callback(selectbox.arrIds(currentSelect.selectItems));
        }
    });
    selectbox.init();
    return selectbox;
});